import os
import json
import subprocess
from pathlib import Path

from utils import fill_ddg_into_code

def run_c_module_and_capture_output(c_file, include_dirs):
    """Run Python modules and capture output"""
    try:
        # Using subprocess to call Python modules and obtain output
        result = subprocess.run(
            ['python3', '-m', 'c-ddg', '--filename', c_file, '--include', ":".join(include_dirs)],
            text=True,
            capture_output=True,
            check=True
        )
        ddg = json.loads(result.stdout)
        return ddg
    except subprocess.CalledProcessError as e:
        print(f"Error processing file {c_file}: {e}")
        return None

def save_c_output_to_json(c_file, ddg, output_dir):
    """Save the output to a separate JSON file"""
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    output_path = Path(output_dir) / (Path(c_file).stem + "_output.json")
    # Check if the file exists, if so, load the content
    if output_path.exists():
        with open(output_path, 'r') as f:
            data = json.load(f)
    else:
        data = {}
    
    if "C" in data:
        if "code" in data["C"]:
            code_dict = data["C"]["code"]
            fill_ddg_into_code(code_dict, ddg)
        data["C"]["DDG"] = ddg
    else:
        data["C"] = {
            "DDG": ddg
        }

    with open(output_path, 'w') as f:
        json.dump(data, f, indent=4)
    print(f"ddg saved to {output_path}")

def ddg_entry(c_file, output_dir, include_dirs):
    print(f"Extract ddg.")
    ddg = run_c_module_and_capture_output(c_file, include_dirs)
    if ddg is not None and ddg:
        save_c_output_to_json(c_file, ddg, output_dir)
    else:
        if c_file.endswith(".h"):
            save_c_output_to_json(c_file, output, output_dir)
        else:
            print(f"The extraction result of {c_file} is empty, ignore it!")
    
# if __name__ == "__main__":
#     import sys
#     if len(sys.argv) != 3:
#         print("Usage: python script.py <c-directory-to-scan> <output-directory>")
#     else:
#         from utils import system_header_paths
#         ddg_entry(sys.argv[1], sys.argv[2], system_header_paths)


def test_parse_ddg():
    import sys
    import os
    
    # 设置测试源文件和输出目录路径
    test_source_file = "test_files/src/test.c"
    test_output_dir = "test_files/output"
    
    # 创建输出目录
    os.makedirs(test_output_dir, exist_ok=True)
    
    # 模拟命令行参数
    sys.argv = [
        "parse_ddg.py",
        test_source_file,
        test_output_dir
    ]
    
    # 调用原main函数的逻辑
    from utils import system_header_paths
    ddg_entry(sys.argv[1], sys.argv[2], system_header_paths)

if __name__ == "__main__":
    test_parse_ddg()